package security;

import dinamica.*;
import dinamica.security.*;

/**
 * Class description.
 * <br>Menu builder<br>
 * @author j.Concept, C.A. (info@j-concept.com)
 * */
public class MenuOutput extends GenericOutput
{

	/* (non-Javadoc)
	 * @see dinamica.GenericOutput#print(dinamica.TemplateEngine, dinamica.GenericTransaction)
	 */
	public void print(TemplateEngine te, GenericTransaction data)
		throws Throwable
	{
		
		//reuse superclass code
		super.print(te, data);
		
		//load section treeview
		StringBuffer bufTreeView = new StringBuffer();
		String section_tree = getResource("section_tree.txt");
		TemplateEngine teMenu;

		//retrieve main recordset (menu titles)
		Recordset menu = data.getRecordset("menu");
		menu.first();
		do
		{

			//load repeatable subtemplate
			GetMenu m = (GetMenu)data;
			String section_folder = getResource("section_folder.txt");		
			teMenu = new TemplateEngine(getContext(),getRequest(), section_folder);
			teMenu.replace(menu,"");
			teMenu.replace("{menu_items}", printItems(m, m.getMenuItems(menu)));
			bufTreeView.append(teMenu.toString());

		}
		while (menu.next());

		teMenu = new TemplateEngine(getContext(),getRequest(), section_tree);
		teMenu.replace("{section_folder}", bufTreeView.toString());

		//replace into main template
		te.replace("${menu}", teMenu.toString());
	}

	private String printItems(GetMenu m, Recordset items)
		throws Throwable
	{
		StringBuffer bufItems = new StringBuffer();
		TemplateEngine teItems;
		String section;		

		while (items.next())
		{
			if (items.getString("class").equalsIgnoreCase("file"))
			{
				section = getResource("section_item.txt");		
				teItems = new TemplateEngine(getContext(),getRequest(), section);
				teItems.replace(items,"");
				bufItems.append(teItems.toString());
			}
			else if (items.getString("class").equalsIgnoreCase("folder"))
			{
				section = getResource("section_folder.txt");		
				teItems = new TemplateEngine(getContext(),getRequest(), section);
				teItems.replace(items,"");
				teItems.replace("{menu_items}", printItems(m, m.getMenuItems(items)));
				bufItems.append(teItems.toString());

			}				
		}
		return bufItems.toString();
	}
}
